import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { throwHttpException1 } from '@/utils/nesjUtils';

// 校验入参
@Injectable()
class CheckParamIsEmptyMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    // 1、校验整体参数是否传递
    if (Object.keys(req.body).length == 0) {
      throwHttpException1({
        state: '0',
        msg: '请检查参数是否正确！',
        data: '',
      });
    }
    const requiredFields = [
      { name: '页码值', field: 'PageIndex' },
      { name: '页码大小', field: 'PageSize' },
      { name: '高级过滤', field: 'AdvancedFilter' },
      { name: '高级排序', field: 'AdvancedSort' },
      { name: '默认查询', field: 'DefaultInputFilter' },
      { name: '高级过滤类型', field: 'AdvancedFilterType' },
    ];
    const bodyKeys = Object.keys(req.body);
    const errFields = requiredFields.filter((f) => {
      if (!bodyKeys.includes(f.field)) {
        return f;
      }
    });

    if (errFields.length != 0) {
      throwHttpException1({
        state: '0',
        msg: `请检查参数是否正确！必填项: ${errFields.map((f) => f.name).join('、')}`,
        data: '',
      });
    }

    next();
  }
}

// @Injectable()
// class CheckIDIsExistMiddleware implements NestMiddleware {
//   async use(req: Request, res: Response, next: NextFunction) {
//     // 1、校验整体参数是否传递
//     const body = req.body as { ID: string };
//     const baseUserList = await prismaClient.base_user.findMany({
//       where: {
//         ID: body.ID,
//         IsDel: '0',
//       },
//     });

//     if (baseUserList.length == 0) {
//       throwHttpException({
//         errcode: ErrCode.ParamsError,
//         errmsg: `请检查参数是否正确！以下ID未找到: ${body.ID}`,
//         errstack: '',
//       });
//     }

//     next();
//   }
// }

export default {
  CheckParamIsEmptyMiddleware,
  // CheckIDIsExistMiddleware,
};
